const jwt = require("jsonwebtoken"),
    dayjs = require("dayjs"),
    { validationResult } = require("express-validator"),
    bcrypt = require("bcryptjs");

const authService = require("../service/authService"),
    utils = require("../utils");

class AuthController {
    // 注册
    async register(req, res, next) {
        try {
            const { username, password } = req.body;

            const errors = validationResult(req);
            if (!errors.isEmpty()) throw new Error(errors.array()[0].msg);

            const id = utils.getSnowId();
            await authService.create({
                username,
                password: bcrypt.hashSync(utils.decrypt(password) || password, 10),
                nickname: "默认昵称" + id.slice(10, 15),
                id,
                login_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
            });
            res.send(utils.msgSuccess({ data: "请求成功" }));
        } catch (error) {
            next(error);
        }
    }
    // 登录
    async login(req, res, next) {
        try {
            const { username, password } = req.body;

            const errors = validationResult(req);
            if (!errors.isEmpty()) throw new Error(errors.array()[0].msg);

            await authService.find({ username, password });

            res.send(
                utils.msgSuccess({
                    data: {
                        token: jwt.sign({ username, password }, process.env.SECRET_KEY, { expiresIn: "1h" }),
                    },
                })
            );
        } catch (error) {
            next(error);
        }
    }
}

module.exports = new AuthController();
